package com.example.framework.job;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;;
import com.example.common.enums.CodeEnum;
import com.example.common.exception.ServiceException;
import com.example.system.entity.User;
import com.example.system.mapper.UserMapper;
import com.example.system.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author 王鹤蒲
 * @Date 2023 11 21
 */
@Component
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
@Slf4j
public class UserStatusMonitoringJob implements Job {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService iUserService;


    @Resource
    private Scheduler scheduler;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDetail jobDetail=jobExecutionContext.getJobDetail();
        JobDataMap jobDataMap=jobDetail.getJobDataMap();
        String userName=jobDataMap.get("config").toString();
        if(!iUserService.isAccountLocked(userName)){
            LambdaUpdateWrapper<User> lambdaUpdateWrapper=new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(User::getUserName,userName);
            lambdaUpdateWrapper.set(User::getStatus,1);
            userMapper.update(new User(),lambdaUpdateWrapper);
            log.info("账号（"+userName+"）已解锁");
            JobKey jobKey =jobDetail.getKey();
            try {
                scheduler.deleteJob(jobKey);
            } catch (SchedulerException e) {
                throw new ServiceException(CodeEnum.TIMING_TASK_ERROR.getCode(),CodeEnum.TIMING_TASK_ERROR.getMsg());
            }
        }

    }
}
